package com.enqualcomm.kids.activities;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.mvp.heartrate.IHeartRateView;
import com.enqualcomm.kids.mvp.heartrate.MyAdapter;
import com.enqualcomm.kids.mvp.heartrate.Presenter;
import com.enqualcomm.kids.network.socket.response.HeartRateQueryResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.enqualcomm.kids.view.chatline.MyLineChartView;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import lecho.lib.hellocharts.listener.LineChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.Viewport;

/**
 * Created by Sunzhigang on 2016/7/19.
 */
@EActivity(R.layout.activity_heart_rate)
public class HeartRateActivity extends BaseActivity implements IHeartRateView {

    @ViewById(R.id.chart)
    MyLineChartView chart;
    @ViewById(R.id.recyclerView)
    RecyclerView recyclerView;
    @ViewById(R.id.locus_date_rl)
    RelativeLayout locus_date_rl;
    @ViewById(R.id.locus_today_btn)
    TextView locus_today_btn;
    @ViewById(R.id.title_bar_right_iv)
    ImageView title_bar_right_iv;

    @Extra("terminal")
    TerminallistResult.Terminal terminal;
    List<HeartRateQueryResult.Result> results;
    Presenter presenter;
    PopupWindow popupWindow;
    MaterialCalendarView calendarView;
    int selectedYear;
    int selectedMonth;
    int selectedDay;
    String todayDateStr;
    int todayYear;
    int todayMonth;
    int todayDay;

    @AfterViews
    void setupViews() {
        presenter = new Presenter(terminal.terminalid);
        presenter.attachView(this);
        initView();

        results = new ArrayList<>();
        updateChartView();
        presenter.queryHeartRate(selectedYear + "-" + selectedMonth + "-" + selectedDay);
    }

    @Click(R.id.heart_rate_btn_iv)
    void remoteQueryHeartRate() {
        presenter.remoteQueryHeartRate();
    }

    @Click(R.id.title_back_iv)
    void goFinish() {
        finish();
    }

    @Click(R.id.title_bar_right_iv)
    void goSettings() {
        startActivityWithTerminal(HeartRateSettingActivity_.class, terminal);
    }

    @Click(R.id.locus_today_btn)
    void queryHeartRate() {
        if (popupWindow == null) {
            View locusView = View.inflate(this, R.layout.pop_locus_date, null);
//            locusView.setBackgroundColor(Color.argb(0xaa,0x1c,0x1c,0x1c));
            calendarView = (MaterialCalendarView) locusView.findViewById(R.id.calendarView);
            calendarView.setTopbarVisible(false);
            calendarView.setDynamicHeightEnabled(true);
            calendarView.setWeekDayLabels(new CharSequence[]{getString(R.string.short_week_sunday), getString(R.string.short_week_monday)
                    , getString(R.string.short_week_tuesday), getString(R.string.short_week_wednesday), getString(R.string.short_week_thursday)
                    , getString(R.string.short_week_firday), getString(R.string.short_week_saturday)});


            //设置能选择的范围
            Calendar calendar = Calendar.getInstance();
            calendar.set(todayYear, todayMonth - 1, todayDay);
            calendar.add(Calendar.MONTH, -3);
            calendarView.setMinimumDate(calendar);//往前3个月
            calendarView.setMaximumDate(new CalendarDay(todayYear, todayMonth - 1, todayDay));//今天

            calendarView.setOnDateChangedListener(new OnDateSelectedListener() {
                @Override
                public void onDateSelected(MaterialCalendarView widget, CalendarDay date, boolean selected) {
                    popupWindow.dismiss();
                    selectedYear = date.getYear();
                    selectedMonth = date.getMonth() + 1;
                    selectedDay = date.getDay();
                    String dateStr = selectedYear + getString(R.string.location_year) + selectedMonth + getString(R.string.location_month) + selectedDay + getString(R.string.location_day);
                    if (dateStr.equals(todayDateStr)) {
                        locus_today_btn.setText(getString(R.string.today));
                    } else {
                        locus_today_btn.setText(dateStr);
                    }

                    presenter.queryHeartRate(selectedYear + "-" + selectedMonth + "-" + selectedDay);
                }
            });

            popupWindow = new PopupWindow(locusView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        calendarView.setSelectedDate(new CalendarDay(selectedYear, selectedMonth - 1, selectedDay));// 根据locus_today_btn显示的日期来设置,每次弹出都要修改!
        popupWindow.showAsDropDown(locus_date_rl);
    }

    MyAdapter adapter;

    private void initView() {
        setupTitleIcon(new UserTerminalDefault(terminal.userterminalid).getInfo(), terminal.terminalid, terminal.userterminalid, "心率");
        title_bar_right_iv.setImageResource(R.drawable.reai_bill_setting);

        /*初始化日期选择*/
        Calendar calendar = Calendar.getInstance();
        todayYear = selectedYear = calendar.get(Calendar.YEAR);
        todayMonth = selectedMonth = calendar.get(Calendar.MONTH) + 1;
        todayDay = selectedDay = calendar.get(Calendar.DAY_OF_MONTH);

        todayDateStr = selectedYear + getString(R.string.location_year) + selectedMonth + getString(R.string.location_month) + selectedDay + getString(R.string.location_day);
        locus_today_btn.setText(getString(R.string.today));

        /*初始化表格*/
        chart.setZoomEnabled(false);
        chart.setValueSelectionEnabled(true);
        chart.setMaximumViewport(new Viewport(0, 200, 24, 0));
        /*初始化recycleView*/
        adapter = new MyAdapter(this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    private void updateChartView() {
//        results = generateData();
        adapter.setData(results);
        ArrayList<PointValue> values = new ArrayList<>();
        for (HeartRateQueryResult.Result result : results) {
            String[] split = result.time.split(":");
            float x = Integer.parseInt(split[0]) * 3600 + Integer.parseInt(split[1]) * 60 + Integer.parseInt(split[2]);
            float y = Float.parseFloat(result.heartrate);
            values.add(new PointValue(x / 3600, y));
        }
        Line line = new Line(values).setColor(Color.parseColor("#FF4444")).setStrokeWidth(1).setHasLines(true).setHasPoints(true).setPointRadius(1);
        ArrayList<Line> lines = new ArrayList<>();
        lines.add(line);
        LineChartData lineChartData = new LineChartData();
        lineChartData.setLines(lines);

        ArrayList<AxisValue> axisValuesLeft = new ArrayList<>();
        axisValuesLeft.add(new AxisValue(20));
        axisValuesLeft.add(new AxisValue(40));
        axisValuesLeft.add(new AxisValue(60));
        axisValuesLeft.add(new AxisValue(80));
        axisValuesLeft.add(new AxisValue(100));
        axisValuesLeft.add(new AxisValue(120));
        axisValuesLeft.add(new AxisValue(140));
        axisValuesLeft.add(new AxisValue(160));
        axisValuesLeft.add(new AxisValue(180));
        axisValuesLeft.add(new AxisValue(200));
        Axis axisLeft = new Axis();
        axisLeft.setValues(axisValuesLeft);
        axisLeft.setHasLines(true);
        axisLeft.setTextColor(Color.BLACK);
        lineChartData.setAxisYLeft(axisLeft);

        ArrayList<AxisValue> axisValuesBottom = new ArrayList<>();
        axisValuesBottom.add(new AxisValue(2));
        axisValuesBottom.add(new AxisValue(4));
        axisValuesBottom.add(new AxisValue(6));
        axisValuesBottom.add(new AxisValue(8));
        axisValuesBottom.add(new AxisValue(10));
        axisValuesBottom.add(new AxisValue(12));
        axisValuesBottom.add(new AxisValue(14));
        axisValuesBottom.add(new AxisValue(16));
        axisValuesBottom.add(new AxisValue(18));
        axisValuesBottom.add(new AxisValue(20));
        axisValuesBottom.add(new AxisValue(22));
        Axis axisBottom = new Axis();
        axisBottom.setValues(axisValuesBottom);
        axisBottom.setHasLines(true);
        axisBottom.setTextColor(Color.BLACK);
        lineChartData.setAxisXBottom(axisBottom);

        chart.setLineChartData(lineChartData);
        chart.setCurrentViewport(new Viewport(0, 200, 24, 0));
        chart.setOnValueTouchListener(new LineChartOnValueSelectListener() {
            @Override
            public void onValueSelected(int lineIndex, int pointIndex, PointValue value) {
                recyclerView.scrollToPosition(pointIndex);
            }

            @Override
            public void onValueDeselected() {
            }
        });
    }

    @Override
    public void updateHeartRate(List<HeartRateQueryResult.Result> results) {
        if (results != null) {
            this.results = results;
            updateChartView();
        }
    }

    @Override
    public void updateAutoHeartRate(HeartRateQueryResult.Result result) {
        if (result!=null){
            //如果日期是当天
            if (isToday(result.datetime)){
                results.add(result);
                updateChartView();
            }
        }else {
            // 手表已关机
        }
    }

    private boolean isToday(String datetime){
        String[] split = datetime.split(" ")[0].split("-");
        if (Integer.parseInt(split[0])==selectedYear &&
                Integer.parseInt(split[1])== selectedMonth &&
                Integer.parseInt(split[2])== selectedDay){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public void error() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (presenter != null){
            presenter.attachView(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        presenter.disAttachView();
    }

//    private ArrayList<HeartRateQueryResult.Result> generateData() {
//        ArrayList<HeartRateQueryResult.Result> results = new ArrayList<>();
//
//        for (int j = 0; j < 96; ++j) {
//            HeartRateQueryResult.Result result = new HeartRateQueryResult.Result();
//            result.heartrate = String.valueOf((int) (Math.random() * 200f));
//            int hour = j / 4;
//            int minute = (j % 4) * 15;
//            result.time = String.format("%02d:%02d:01", hour, minute);
//            results.add(result);
//        }
//        return results;
//    }
}
